<?php
namespace app\index\controller;
use app\common\enums\ResultEnum;
use app\common\utils\ResultVOUtil;
use think\Request;
use app\common\service\AccountService;
use app\common\service\UserService;

class Account extends Base{
    private $accountService;
    private $userService;
    
    public function __construct(AccountService $accountService,UserService $userService)
    {
        
        $this->accountService = $accountService;
        $this->userService = $userService;
    }

    public function index(Request $request){
        $param = $request->param();
        $where = [];
        
        if(!empty($param)){
            if ( !empty($param['search']) ) {
                
                $where[] = ['trade_no','like','%'.$param['search'].'%'];
            }
            
            if ( !empty($param['charge_status']) ) {
                $where[] = ['charge_status','=',$param['charge_status']];
            }

            $userData = $this->userService->list();
            $userId = array_column(json_decode($userData,true), 'id');       
            
            if ( !empty($param['user_id']) && in_array($param['user_id'], $userId)) {
                $where[] = ['user_id','=',$param['user_id']];
            }else{
                
                $where[] = ['user_id','in',$userId];
            }
            
            $data = $this->accountService->index($where,$param['page'],$param['length']);
            
            if($data){
                return ResultVOUtil::success($data);
            }else{
                return ResultVOUtil::error(ResultEnum::FIND_ERROR);
            }
        }
    }
    
    public function details($accountId){
        $data = $this->accountService->details($accountId);
        if($data){
            return ResultVOUtil::success($data);
        }else{
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }
    }

    public function save(Request $request){
        $param = $request->param();
        if(!empty($param)){
            $data = $this->accountService->save($param);
            if($data){
                return ResultVOUtil::success('');
            }else{
                return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
            }
        }
        
    }
    
}